package com.pkk.components.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;


/**
 * @description: 解析yml
 * @author: peikunkun
 * @create: 2018-09-08 14:57
 **/
public class YmlParserUtil {

    private static Map<String, String> allMap = new HashMap<String, String>();


    public static Map<String, String> parserYmlToProperties(String ymlSource) {
        return makeParserYml(ymlSource);
    }

    public static Map<String, String> parserYmlToProperties(InputStream ymlSource) {
        return makeParserYml(ymlSource);
    }

    private static Map<String, String> makeParserYml(Object object) {
        allMap.clear();

        if (object == null) {
            return allMap;
        }
        InputStream inputStream = null;
        if (object instanceof InputStream) {
            inputStream = (InputStream) object;
        }
        if (object instanceof String) {
            inputStream = YmlParserUtil.class.getResourceAsStream(object.toString());
        }
        Yaml yaml = new Yaml();
        Iterator<Object> result = yaml.loadAll(inputStream).iterator();
        while (result.hasNext()) {
            Map map = (Map) result.next();
            iteratorYml(map, null);
        }
        return allMap;
    }


    public static void main(String[] args) {
        System.out.println(YmlParserUtil.allMap);
        String ss = allMap.get("spring.profiles");
        System.out.println(ss);
    }

    /**
     * @Description: 把yml格式转换为properties格式
     * @Param: [map, key]
     * @return: void
     * @Author: peikunkun
     * @Date: 2018/9/8 0008 下午 3:03
     */
    private static void iteratorYml(Map map, String key) {
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object key2 = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof LinkedHashMap) {
                if (key == null) {
                    iteratorYml((Map) value, key2.toString());
                } else {
                    iteratorYml((Map) value, key + "." + key2.toString());
                }
            }

            //设置值
            if (key == null) {
                allMap.put(key2.toString().trim(), value.toString().trim());
            }
            if (key != null) {
                allMap.put(key.trim() + "." + key2.toString().trim(), value.toString().trim());
            }
        }

    }

}
